import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { Prisma, course, user_course,course_chapter } from '@prisma/client';
@Injectable()
export class UserCourseService {
  constructor(private readonly prisma: PrismaService) { }
  getCourseList(userId: string) {
    return this.prisma.user_course.findMany({
      where: {
        userId: userId
      },
      include: {
        course: true,
      }
    });
  }
  async getCourseDetail(userId: string, courseUserId: string) {
     let courseDetail  =  await this.prisma.user_course.findFirst({
      where: {
        userId: userId,
        id: courseUserId
      },
      include: {
        course: true,
      }
    });
    if (!courseDetail) {
      throw new NotFoundException('课程不存在');
    }
    const courseChapter = await this.prisma.course_chapter.findMany({
      where: {
        courseId: courseDetail.courseId,
      },
      include: {
        userChapter: {
          take: 1,  // 只查询关联的第一条记录
        }
      }
    });
    // 将userCourseChapters数组转换为单个对象
    const formattedChapters = courseChapter.map(chapter => {
      const userStudy = chapter.userChapter[0] || []
      return {
        ...chapter,
        userCourseChapters: userStudy
      };
    });
    return {
      ...courseDetail,
      courseChapter: formattedChapters
    }
  }
  async getUserOpenCourse(userId: string, courseId: string) {
    const relust = await this.prisma.user_course.findFirst({
      where: {
        userId: userId,
        courseId: courseId,
      }
    });
    return relust === null?'':relust.id ;
  }
  async submitOpenCourse(userId: string, courseId: string) {
    const userCourse = await this.getUserOpenCourse(userId, courseId);
    const chapterCount = await this.prisma.course_chapter.count({
      where: {
        courseId: courseId
      }
    })
    if (userCourse) {
      throw new NotFoundException('该课程已开通');
    }
    await this.prisma.user_course.create({
      data: {
        courseId: courseId,
        userId: userId,
        schedule:{
          chapterNum: chapterCount,
          chapterEnd: 0,
          chapterRatio:0
        }
     
      }
    })
    return { statusCode: 200, message: '开课成功，请前往学习!' };
  }
}
